package org.neogenesis.web.controller;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.enterprise.context.ConversationScoped;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.SessionScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import javax.xml.bind.JAXBException;

import org.neogenesis.web.Configurations;
import org.neogenesis.web.dao.GEOSeriesDAO;
import org.primefaces.component.dialog.Dialog;
import org.primefaces.event.FileUploadEvent;

@Named("series")
@SessionScoped
public class GEOSeriesController implements Serializable {

	private String fileName;

	@Inject
	private GEOSeriesDAO geoSeriesDAO;

	public void handleFileUpload(FileUploadEvent event) {
		FacesMessage msg = new FacesMessage("Succesful", event.getFile()
				.getFileName() + " is uploaded.");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		byte[] content = event.getFile().getContents();
		fileName = event.getFile().getFileName();
		try {
			saveFile(fileName, content);
		} catch (FileNotFoundException ex) {
			Logger.getLogger(PlatformController.class.getName()).log(
					Level.SEVERE, null, ex);
		} catch (IOException ex) {
			Logger.getLogger(PlatformController.class.getName()).log(
					Level.SEVERE, null, ex);
		}
	}

	private void saveFile(String name, byte[] content)
			throws FileNotFoundException, IOException {

		String webAppPath = FacesContext.getCurrentInstance()
				.getExternalContext().getRealPath("/");

		String filePath = webAppPath + Configurations.uploadPath;
		FileOutputStream fos = new FileOutputStream(filePath + name);
		fos.write(content);
		fos.flush();
		fos.close();
	}

	public String create() {

		if (!geoSeriesDAO.init(fileName))
			return "errorInSeries";
		

		if (!geoSeriesDAO.loadPlatforms())
			return "errorLoadPlatform";
		
		if (!geoSeriesDAO.loadExperiment())
			return "duplicateExperiment";
		
		if (!geoSeriesDAO.loadSamples())
			return "errorLoadSamples";
		
		geoSeriesDAO.deleteFiles();
		fileName = "";

		return "okSeries";
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
}
